异步混合:
为了建立异步处理机制,需要使用ThreadingMixIn和ForkingMixIn类。
以下是一个使用ThreadingMixIn类的示例:
<strong>import socket
import threading
import socketserver
class ThreadedTCPRequestHandler(socketserver</strong><span style="color:#cc0000;">.BaseRequestHandler):
</span>
<span style="color:#ff0000;"> def handle(self):
</span><strong> data = str(self.request.recv(1024), 'ascii')
cur_thread = threading.current_thread()
response = bytes("{}: {}".format(</strong><span style="color:#ff0000;">cur_thread.name, data</span><strong>), 'ascii')
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn,</strong> <span style="color:#ff0000;"><strong>socketserver.TCPServer):</strong>
</span><strong> pass
def client(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(bytes(message, 'ascii'))
response = str(sock.recv(1024), 'ascii')
print("Received: {}".format(response))
finally:
sock.close()
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0</strong>
<span style="color:#ff0000;">server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
</span><span style="color:#ff0000;"> ip, port = server.server_address
</span><strong>
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(</strong><span style="color:#ff0000;">target=server.serve_forever</span><strong>)
# Exit the server thread when the main thread terminates</strong>
<span style="color:#ff0000;">server_thread.daemon = True
server_thread.start()
</span><strong> print("Server loop running in thread:", server_thread.name)</strong>
<span style="color:#ff0000;">client(ip, port, "Hello World 1")
client(ip, port, "Hello World 2")
client(ip